import router_conf from '../../config/router'
import Router from '../../utils/router';
import base from '../../config/base.js';
import service from '../../services/store';
import service_group from '../../services/groupdragon';
import util from '../../utils/util.js';
import Record_server from '../../services/record-stat';
import Record from '../../utils/page-record.js';
import conf_conf from '../../config/config.js';
import ext from '../../utils/login';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    closes:false,
    icon_nav_entrance1: base.static + 'store/cutprice-icon.png',//首页入口
    icon_nav_entrance2: base.static + 'store/qunjielong.png',
    icon_nav_entrance3: base.static + 'store/qinadao.png',
    icon_nav_entrance4: base.static + 'store/mianfeichou.png',
    icon_nav_entrance5: base.static + 'store/beike.png',
    icon_nav_entrance6: base.static + 'store/zhuangbeike.png',
    icon_nav_entrance7: base.static + 'store/guafenbeike3.png',
    icon_nav_news: base.static + 'store/nav-news.png',
    icon_nav_entrance8: base.static + 'store/bushudui.png', 
    icon_nav_entrance9: base.static + 'store/nav-icon-overseas.png', 
    icon_nav_entrance10: base.static + 'store/specialarea.png', //首页入口
    icon_store_auth: base.static + 'store/store-auth.png',
    icon_mask_sellout: base.static + 'store/csellout.png',
    sharefirend_bg: base.static + 'store/sharefiend-bg8.png',
    logo: base.static + 'store/logo.png',
    icon_red_banner: base.static + 'store/red-banner.jpg',
    icon_receive_red: base.static + 'task/red-nored2.png',
    icon_ylingqu: base.static + 'my/ylingqu.png',
    icon_coupon_ky: base.static + 'my/coupon_ky.png',
    icon_ac_redopen_bg: base.static + 'store/openred-bg.png',
    icon_ac_redopen_btn: base.static + 'store/openred.png',
    icon_news_quan: base.static + 'store/news-quan.png',
    icon_ac_red_close: base.static +'store/ac-redclose.png',
    icon_tehui_top: base.static + 'store/tehui-top.png',
    icon_tehui_jinbo: base.static + 'store/lowmoney2.png',
    icon_tehui_jinbo_goodslist: base.static + 'store/lowmoney3.png',
    icon_red_ban_yuan: base.static + 'store/red-ban-yuan2.png', 
    icon_share_store: base.static + 'store/sharestore2.png',
    icon_group_dragon: base.static + 'store/gorupDragon.png',
    icon_search: base.static + 'choose/search3.png',
    icon_goluck_close: base.static + 'store/go-luck-close.png',
    icon_goluck: base.static + 'store/go-luck.png',
    isShowFavorite: false,
    favorite: base.static + 'index/favorite.png',
    store_share_img: base.static + 'store/newshare.jpg',
    scrolltop: '',
    avatar: '',
    avatar_bg: '',
    store_id: '',
    store_name: '',
    user_nickname: '',
    endAllBloon: false, //好物节流
    loadAllBloon: true,
    nomore: true,
    pageAll: 1,
    goodsall: [],
    hottodyList: [],
    endHotBloon: false,
    loadHotBloon: true,
    pageHot: 1,
    close: false,
    newsList: '', //新人优惠券
    userid: '',
    isShowTips: false,
    transmitRed:{
      style:'position:absolute;width:160rpx;height:160rpx;left:300rpx;top:650rpx;opacity:0;',
      value:''
    },
    transmit: {
      style: 'position:absolute;width:100%;height:100%;right:0rpx;top:0rpx;opacity:0;',
      value: ''
    },
    cheap_goodsBloon: false, //2.0特惠专区是否显示
    SpecialareaList: [], //2.0特惠专区列表
    openAcRed: false, //2.0活动红包打开是否显示
    receiveAcRed: false, //.0活动红包领取是否显示
    receivAlready: false, //2.0红包是否领取过
    receiveRedList: '', //2.0红包领取记录
    receiveNewsList: [], //2.0优惠券领取记录
    bybsid: '', //2.0红包id
    customer_banner_activiety: 2,
    customer_preferential_goods: 2,
    tempFilePathAvatar: '', //下载分享朋友圈图片头像备用图
    isShenhe: '',
    conchList: '', //2.6贝壳特惠
    pageName: 'store',
    doubleElevenList: '', //2.10.0双11列表
    doubleElvenBottomLeveTop: '', //双11特惠列表底部距离顶部高度
    doubleElvenLeveTop: '',//双11特惠列表头部距离顶部高度
    groupList: '', //2.10.0群接龙
    loadsSevenSingBloean: 1,
    goLuckBloon: false, //2.22.0是显示去抽奖
   },
  /*
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    that.setData({
      loadAllBloon: true,
      goodsall: [],
      pageAll: 1,
      hottodyList: [],
      loadHotBloon: true,
      pageHot: 1,
      SpecialareaList: [], //2.0特惠专区列表
      receiveNewsList: [], //2.0优惠券领取记录
      isShowTips: false,
      isShenhe: wx.getStorageSync('isShenhe'),
      loadsSevenSingBloean: 2,
    });
    
    // 从消息提醒进入
    if (options && options.to) {
      let to = decodeURIComponent(options.to);
      let arr_url = to.split('?');
      let page_name = '',
        method = 'navigateTo';
       for (let i in router_conf) {
        if(router_conf[i].url == `${arr_url[0]}`){
          page_name = i+'';
          break;
        }
       }
      Router.go(page_name, arr_url.length == 2 ? arr_url[1] : '', method);
    }

    //从2.0分享红包连接进入
    if (options && options.bybsid){
      that.setData({
        bybsid: options.bybsid,
        openAcRed: true,
      })
      that.customerInfo(options.customer_id)
    }else{
      //判断是否是新用户
      that.newUser(function () {
        // 抽奖弹框判断
        that.checkGoLuck(function(){
          that.openFavorite();
        })
      });
    }

    that.setData({
      auth_token: 'auth_token=' + wx.getStorageSync('auth_token'),
      userid: wx.getStorageSync('user_info').id,
      user_info: wx.getStorageSync('user_info'),
      activity: wx.getStorageSync('activity'),
    });
    if (wx.getStorageSync('activity').customer_banner_activity && wx.getStorageSync('activity').customer_preferential_goods){
      that.setData({
        customer_banner_activiety: wx.getStorageSync('activity').customer_banner_activity,
        customer_preferential_goods: wx.getStorageSync('activity').customer_preferential_goods,
      })
    }
    
    this.opt(options);
    this.getcheap_status(); //2.0红包活动状态
    //下载分享朋友圈图片头像备用图
    wx.downloadFile({
      url: base.static + 'store/logo2.png', 
      success: function (res) {
        if (res.statusCode === 200) {
          that.setData({
            tempFilePathAvatar: res.tempFilePath
          })
        }
      }
    })
  },
  //点击返回自己店铺时方法
  back_myShop(){
    let user_infoStoreId = wx.getStorageSync('user_info').store_id;
    Router.reLaunch('store', `store_id=${user_infoStoreId}`, 'reLaunch');
  },
  //去签到贝壳页面//去瓜分贝壳页面//步数兑换贝壳页面
  navGo(e){
    let that = this;
    Router.go(e.currentTarget.dataset.url, `store_id=${that.data.store_id}`)
  },
  openFavorite: function(){
    // 展示收藏弹层 = 不展示新手红包 && 大于6.7.0 && 第二次进入小程序
    let sysinfo = wx.getSystemInfoSync();
    if (this.data.close == false && util.versionCompare(sysinfo.version, '6.7.0') && wx.getStorageSync('userCount') == 3) {
      wx.setStorageSync('userCount',4)
      this.setData({
        isShowFavorite: true
      })
    }
  },
  hideFavorite: function () {
    this.setData({
      isShowFavorite: false
    })
  },
  //判断有没有options
  opt: function(options) {
    let that = this;
    let reg = /^[1-9]\d*$/;
    let store_id = options.store_id;
    if (reg.test(store_id)) {
      that.setData({
        store_id: store_id,
      });
      // 加载数据
      that.storeInfo(store_id);
      that.storeListAll(store_id, 1);//店主精挑
      // that.getStoreImg(store_id);
      that.getConch();
    } else {
      wx.getStorage({
        key: "user_info",
        success: function(res) {
          try{
            if (res && res.data && res.data.lastView && res.data.lastView.seid && reg.test(res.data.lastView.seid)) {
              that.setData({
                store_id: res.data.lastView.seid,
              });
              // 加载数据
              that.storeInfo(res.data.lastView.seid);
              that.storeListAll(res.data.lastView.seid, 1);//店主精挑
              // that.getStoreImg(res.data.lastView.seid);
              that.getConch();
              let p = getCurrentPages().pop();
              let ss = 'have_lastView_success' + JSON.stringify(res.data)
              Record.pagesOptions(ss, p)
            } else {
              let p = getCurrentPages().pop();
              let resStr = res.data && res.data.lastView ? JSON.stringify(res.data.lastView) : 'kkkk';
              let ss = 'no_lastView_success' + resStr
              Record.pagesOptions(ss, p)
              wx.showModal({
                title: '提示',
                content: '没有找到相对应的店铺,请重新启动',
                success(res) {
                  ext.quit();
                  Router.reLaunch('store', ``, 'reLaunch');
                }
              })
            }
          }catch(e){}
        },
        fail() {
          let p = getCurrentPages().pop();
          Record.pagesOptions('no_lastView_fail', p)
          wx.showModal({
            title: '提示',
            content: '没有找到相对应的店铺,请重新启动',
            success(res) {
              ext.quit();
              Router.reLaunch('store', ``, 'reLaunch');
            }
          })
          
        }
      })
    }
    //在非自己店铺浏览时的提示
    wx.getStorage({
      key: 'user_info',
      success: function(res) {
        let user_infoStoreId = res.data.store_id;
        if (that.data.store_id != user_infoStoreId && user_infoStoreId != null) {
          that.setData({
            isShowTips: true
          })
        }
      },
    })
  },
  //分享店铺
  shareStore: function() {
    let that = this;
    let share = {
      isShow: true,
      animate: true,
      store_id: that.data.store_id
    }
    that.setData({
      share: share,
      user_info: wx.getStorageSync('user_info'),
      activity: wx.getStorageSync('activity')
    })
  },
  // 商品店铺好物列表
  storeListAll: function(store_id, page) {
    let that = this;
    let params = {
      type: "all",
      store_id: store_id,
      page: page,
      offset: 10
    }
    service.querystorelist(params, function(res) {
      if (res && res.code == 1) {
        let stolistAll = that.data.goodsall.concat(res.data.list);
        that.setData({
          goodsall: stolistAll,
          pageAll: page + 1,
          endAllBloon: true
        });
        if (stolistAll.length == res.data.totalNum) {
          that.setData({
            loadAllBloon: false,
          })
          if (that.data.activity.share_activity == 1){
            //今日热销
            that.storeListHot(that.data.pageHot);
          }else{
            that.setData({
              nomore: false
            })
          }
        }
      }
    });
  },
  // 店铺今日热销列表
  storeListHot: function (page) {
    let that = this;
    let params = {
      page: page,
      per_page: 10
    }
    service.customerRecommend(params, function (res) {
      if (res && res.code == 200) {
        let stolistHot = that.data.hottodyList.concat(res.data.recommend);
        that.setData({
          hottodyList: stolistHot,
          pageHot: page + 1,
          endHotBloon: true
        });
        wx.stopPullDownRefresh();
        if (stolistHot.length == res.data.count) {
          that.setData({
            loadHotBloon: false,
            nomore: false
          })
        }
       
      }
    });
  },
  //店铺信息
  storeInfo: function(store_id) {
    let that = this;
    let params = {
      store_id: store_id
    };
    service.querystoreinfo(params, function(res) {
      if (res && res.code == 1) {
        let stoName = res.data.store_name;
        if (res.data.store_name.length > 8){
          stoName = res.data.store_name.substr(0, 8) + '...';
        }
        let strAvatar = res.data.avatar
        if (res.data.avatar){
          let leng = res.data.avatar.length - 3;
          strAvatar = res.data.avatar.substr(0,leng)
          strAvatar += "0"
        }
        wx.setNavigationBarTitle({
          title: res.data.store_name + '的推荐',
        })
        that.setData({
          avatar_bg: strAvatar, 
          avatar: res.data.avatar,
          store_name: res.data.store_name,
          store_na: stoName,
          user_nickname: res.data.user_nickname,
        });
        wx.stopPullDownRefresh();
      }
    });
  },
  //去商品详情
  goDetail: function(e) {
    let that = this;
    let goods_id = e.currentTarget.dataset.goodsid;
    let store_id = that.data.store_id;
    Router.go('detail', `store_id=${store_id}&goods_id=${goods_id}`);
    that.viewRecord(goods_id, "click");
  },
  //授权弹窗取消
  hidemodal: function() {
    let that = this;
    that.setData({
      show: false
    });
  },
  //返回顶部
  goscoltop: function() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  //判断是否是新用户
  newUser: function(cb) {
    let _this = this;
    let params = {
      type: 'receive_newpeoplecoupon'
    }
    service.receiveaj(params, function(res) {
      if (res.code == 1) {
        _this.setData({
          close: true,
          newsList: res.data
        });
      }else{
        cb();
      } 
    });
  },
  //2.0特惠商品活动状态
  getcheap_status: function () {
    let that = this;
    let params = {}
    service.cheap_status(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          cheap_goodsBloon: true
        })
        that.getcheap_goods();
      } else if (res.code && res.code == 413){
        that.setData({
          cheap_goodsBloon: false
        })
      }
    });
  },
  //2.0特惠专区列表
  getcheap_goods: function () {
    let that = this;
    let params = {}
    service.getcheap_goods(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          SpecialareaList: res.data
        })
      }
    });
  },
  //2.0红包领取列表
  getBountyBonus: function (bybsid){
    let that = this;
    let params = {
      bybsid: bybsid
    }
    service.getBountyBonus(params, function (res) {
      if (res.code == 1) {
        if (res.data.user == "newPeople"){//可以领取
          that.setData({
            receiveRedList: res.data.list,
            receiveNewsList: res.data.newPeople,
          });
        } else if (res.data.user == "oldPeople"){
          that.setData({
            receiveRedList: res.data.list,
          });
        }        
      }else if (res.code == 0){
        that.setData({
          receiveResDataCode: res.data.code,
          receivAlready: true
        });
        if (res.data.code == 10) {//活动未开始或者结束

        } else if (res.data.code == 11) { //暂无该红包信息 

        } else if (res.data.code == 12) { // 每天最多领取5个

        } else if (res.data.code == 13) { // 你已经领取过

        } else if (res.data.code == 14) { // Sorry...你来晚了

        } else if (res.data.code == 15) { // Sorry...你来晚了（新用户 “list”优惠卷字段）
          that.setData({
            receiveNewsList: res.data.list,
          });
        } else if (res.data.code == 16) { // 红包领取失败
          wx.showToast({
            title: '红包领取失败',
          })
        }
        that.setData({
          receiveRedList: res.data.list,
        });
      }
      
    });
  },
  //2.0活动红包点击关闭
  closeAcRed: function(){
    this.setData({
      openAcRed: false,
      receiveAcRed: false
    })
  },
  //2.0活动红包点击领取
  receiveAcRed: function(){
    let that = this;
    that.setData({
      icon_ac_redopen_btn: base.static + 'store/opnered-move.gif',
    });
    setTimeout(function(){
      that.setData({
        openAcRed: false,
        receiveAcRed: true
      })
    },1000)
    that.getBountyBonus(this.data.bybsid);
  },
  //2.0去红包赏金页
  goMyredinfo: function(){
    let store_id = this.data.store_id
    Router.go('myredinfo', `store_id=${store_id}`);
  },
  //根据id获取买家信息
  customerInfo: function (customer_id) {
    let that = this;
    let params = {
      customer_id: customer_id
    }
    service.customerInfo(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          customerInfo_avater: res.data.avatar,
          customerInfo_nickname: res.data.user_nickname, 
        })
      }
    });
  },
  //获取店铺分享图片
  getStoreImg: function (store_id) {
    let that = this;
    let params = {
      store_id: store_id
    }
    service.getstore_share(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          store_share_img: 'https:' + res.data.pic
        })
      }
    });
  },
  //2.6贝壳特惠列表
  getConch: function () {
    let that = this;
    let params = {}
    service.getcheap_goods(params, function (res) {
      if (res.code && res.code == 200) {
        let arr = [];
        for(let i=0; i<res.data.length; i++){
          if (res.data[i].all_num != 0 && res.data[i].all_num ){
            arr.push(res.data[i]);
          }
          if(arr.length >= 3){
            break
          }
        }
        that.setData({
          conchList: arr
        })
      }
    });
  },
  // 2.10.0双11特惠
  getDoubleEleven: function (types) {
    let that = this;
    let params = {
      goods_type: 2
    }
    service.getcheap_goods(params, function (res) {
      if (res.code && res.code == 200) {
        that.setData({
          doubleElevenList: res.data
        });
        
      }
    });
  },
  //2.10.0群接龙列表
  getGroupList: function (store_id) {
    let that = this;
    let params = {
      store_id: store_id,
      page: 1,
      limit: 10
    }
    service_group.groupgoodslist(params, function (res) {
      if (res.code && res.code == 1) {
        let grouplist = res.data.list
        let myDate = new Date();
        let hours = 23 - myDate.getHours()
        grouplist.forEach((item, index)=>{
          let second = ''
          if (item.all_num_status == 1){//有库存
            let floor1 = hours * 3600;
            let floor2 = (hours + 24) * 3600
            let time = item.time
            if (item.time <= floor1){
              let strArr = item.validity_end_time.split("-");
              grouplist[index].time_str = '今日' + strArr[2].split(' ')[1];
            } else if (floor1 < item.time && item.time < floor2) {
              let strArr = item.validity_end_time.split("-");
              grouplist[index].time_str = '明日' + strArr[2].split(' ')[1];
            } else if (item.time > floor2) {
              let strArr = item.validity_end_time.split("-");
              grouplist[index].time_str = strArr[1] + '月' + strArr[2].split(' ')[0] + '日' + strArr[2].split(' ')[1];
            }
          }
        })
        that.setData({
          groupList: grouplist,
        })
        let clientWidth = wx.getSystemInfoSync().windowWidth;
        let clientHeight = wx.getSystemInfoSync().windowHeight;
        let itemHeigth = clientWidth / 750 * 220;
        wx.createSelectorQuery().select('#group').boundingClientRect(function (rect) {
          that.setData({
            doubleElvenLeveTop: rect.top + itemHeigth - clientHeight,
            doubleElvenBottomLeveTop: (rect.height + rect.top - itemHeigth) * 1.5,
          })
        }).exec()
      }
    });
    wx.stopPullDownRefresh()
  },
  //去群接龙详情
  goGroupDetail: function (e) {
    let that = this;
    let goods_id = e.currentTarget.id
    Router.go("dragon", `store_id=${that.data.store_id}&segsid=${e.currentTarget.dataset.segsid}`);
    that.viewRecord(goods_id, 'click')
  },
  //去搜索页面
  goSearch: function(){
    Router.go("search", ``);
    let p = getCurrentPages().pop();
    Record.clickButton(p, 'go_search_button');
  },
  // 去协议
  goAgreement: function () {
    Router.go('web', `url=${encodeURIComponent('https://kpxd.zhengdianhaohuo.com/h5/#/seller/win3_959')}`);
  },
  //获取元素节点信息
  queryMultipleNodes(scrollTop) {
    let that = this;
    let doubleElvenBottomLeveTop = that.data.doubleElvenBottomLeveTop;
    let doubleElvenLeveTop = that.data.doubleElvenLeveTop;
    if (doubleElvenLeveTop < scrollTop && scrollTop < doubleElvenBottomLeveTop) {
      let query = wx.createSelectorQuery();
      let s = wx.getSystemInfoSync().windowHeight;
      query.selectAll('.test').boundingClientRect(function (rects) {
        rects.forEach((item, index) => {
          if (item && 0 < item.top && item.bottom < s){
            that.viewRecord(item.id, "view")
          }
        })
      }).exec()
    }
  },
  //滚动和点击屏幕记录
  viewRecord: function (goodsid, act) {
    let that = this;
    let params = {
      name: "ltxx_buyer",
      page: 'store',
      position: 'group_dragon',
      productid: goodsid,
      userid: that.data.userid,
      storeid: that.data.store_id,
      act: act,
      env: getApp().globalData.env
    }
    Record_server.recordstat(params, function () { });
  },
  // 判断是否显示去抽奖
  checkGoLuck: function(cb){
    let that = this;
    let today = new Date().getDate();
    let todayS = wx.getStorageSync('todayNum')
    if (today != todayS){
      that.setData({
        goLuckBloon: true
      })
      wx.setStorageSync('todayNum', today)
    }else{
      //提示收藏小程序
      cb();
    }
  },
  // 点击去抽奖
  clickGoLuck: function(){
    let that = this;
    that.setData({
      goLuckBloon: false
    })
    Router.go('luck', `store_id=${that.data.store_id}`)
  },
  // 点击关闭抽奖
  closeGoLuck: function () {
    this.setData({
      goLuckBloon: false
    })
  },
  //监听页面高度
  scrollTimer: null,
  onPageScroll: function (e) {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.scrollTimer = setTimeout(() => {
      that.setData({
        scrolltop: e.scrollTop
      })
      // 双11商品曝光
      // that.queryMultipleNodes(e.scrollTop)
    }, 500);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    that.setData({
      show: false,
    });
    // 判断侧边栏签到七天签到
    if (that.data.loadsSevenSingBloean != 1) {
      let loadsSevenSingBloean = that.data.loadsSevenSingBloean + 1
      that.setData({
        loadsSevenSingBloean
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that = this;
    if (that.scrollTimer) {
      clearTimeout(that.scrollTimer)
    };
    that.setData({
      loadAllBloon: true,
      goodsall: [],
      pageAll: 1,
      hottodyList: [],
      loadHotBloon: true,
      nomore: true,
      pageHot: 1,
      SpecialareaList: [], //2.0特惠专区列表
      receiveNewsList: [], //2.0优惠券领取记录
    });
    that.storeListAll(that.data.store_id, 1);
    if (that.data.customer_preferential_goods == 1 && that.data.cheap_goodsBloon){
      that.getcheap_goods();
    }
    // that.getConch();
    that.storeInfo(that.data.store_id);
    // that.getGroupList(that.data.store_id);//群接龙
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    let that = this;
    if (that.data.loadAllBloon && that.data.endAllBloon) {
      that.setData({
        endAllBloon: false
      })
      that.storeListAll(that.data.store_id, that.data.pageAll);
    } else if (that.data.loadHotBloon && that.data.endHotBloon && that.data.activity.share_activity == 1){
      that.setData({
        endHotBloon: false
      })
      that.storeListHot(that.data.pageHot);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    let that = this;
    let user_id = wx.getStorageSync('user_info').id
    withShareTicket: true;
    let id = that.data.store_id;
    let store_name = that.data.store_name;
    let store_share_img = that.data.store_share_img;
    if (store_name.length > 8) {
      store_name = store_name.substr(0, 8) + '...';
    }
    return {
      title: '【' + store_name + '@你' + '】' + '请收下我的这份走心推荐!',
      path: '/pages/store/index?store_id=' + id + '&sharerecord=storecard' + '&user_id=' + user_id,
      // imageUrl: store_share_img
    }
  }
})